<?php

namespace app\modules\admin\controllers;

use app\constants\Code;
use app\extensions\XUtils;
use app\models\Group;
use app\services\GroupService;
use yii;
use yii\data\Pagination;

/**
 * 用户组管理控制器
 * @author chenym
 * @since 2017.7.05
 * Class GroupController
 */
class GroupController extends BaseController
{
    public function init()
    {
        parent::init();
    }

    public function beforeAction($action)
    {
        //$this->enableCsrfValidation = false;//前端自定义表单时，要关闭csrf验证，否则会找不到显示400 Bad Request
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    /**
     * 分组列表
     */
    public function actionIndex()
    {
        $page       = Yii::$app->request->get('page', 1);
        $groupModel = new Group();
        $groupName  = '';
        $params     = [
            'page'  => $page,
            'limit' => Code::ADMIN_PAGE_SIZE,
            'where' => [
                'and',
                ['>', 'id', 0],
            ],
            'order' => 'id DESC'
        ];
        if (!empty($groupName)) {
            $params['where'][] = ['like', 'groupName', $groupName];
        }
        $fields    = [
            'id',
            'groupName',
            'statusIs',
            'createTime',
        ];
        $groupList = $groupModel->dbList($fields, $params);
        $pages     = new Pagination(['totalCount' => $groupList['count'], 'pageSize' => Code::ADMIN_PAGE_SIZE]);
        $assign    = [
            'pages'    => $pages,
            'dataList' => $groupList['list'],
        ];
        return $this->render('index', $assign);
    }

    /**
     * 添加or编辑分组
     */
    public function actionCreate()
    {
        $groupId      = intval(Yii::$app->request->get('groupId', 0));
        $groupName    = '';
        $groupAcl     = [];
        $groupModel   = new Group();
        $groupService = new GroupService();
        if ($groupId) {
            if ($groupId == 1 || $groupId == 2) {
                XUtils::message('error', '此用户组不能编辑', '/admin/group/index');
            }
            $param = [
                'where' => [
                    'id' => $groupId
                ]
            ];
            $check = $groupModel->dbGet('*', '', $param);
            if (empty($check)) {
                XUtils::message('error', '用户组不存在，请重试！', '/admin/group/index');
            }
            $groupName = $check['groupName'];
            $groupAcl  = explode(',', $check['groupAcl']);
        }
        $assign = [
            'groupId'   => $groupId,
            'groupName' => $groupName,
            'groupAcl'  => $groupAcl,
            'model'     => $groupModel,
        ];
        if (Yii::$app->request->isPost) {
            $groupId    = Yii::$app->request->post('groupId');
            $groupName  = Yii::$app->request->post('groupName');
            $acl        = Yii::$app->request->post('acl');
            $checkGroup = $groupService->checkGroupNameIsExists($groupName, $groupId);
            if ($checkGroup) {
                XUtils::message('error', '用户组已存在，请重试！', ($groupId ? "/admin/group/create?groupId={$groupId}" : '/admin/group/create'));
            }
            if (empty($acl)) {
                XUtils::message('error', '请添加权限！', ($groupId ? "/admin/group/create?groupId={$groupId}" : '/admin/group/create'));
            }
            $group['groupAcl']  = implode(',', $acl);
            $group['groupName'] = $groupName;
            if ($groupId) {
                //编辑用户组
                $group['updateTime'] = time();
                $affect              = $groupModel->dbUpdate('', $group, ['where' => 'id=:id', 'bind' => [':id' => $groupId]]);
            } else {
                //新增用户组
                $group['createTime'] = $group['updateTime'] = time();
                $parentId            = Yii::$app->session->get('_adminiGroupId');
                $group['parentId']   = $parentId;
                $affect              = $groupModel->dbAdd($group);
            }
            XUtils::message(($affect ? 'success' : 'error'), ($groupId ? '编辑' : '新增') . ($affect ? '成功' : '失败'), 'index');
        }
        return $this->render('create', $assign);
    }

    /**
     * 删除分组
     */
    public function actionDelete()
    {
        $id     = Yii::$app->request->post('id', 0);
        $return = GroupService::deleteGroup($id);
        exit(XUtils::echoJson($return));
    }
}
